import Food from './food'
import ScorePanel from './score'
import Snake from './snake'

class GameControl {
    food: Food
    snake: Snake
    scorePanel: ScorePanel
    direction: string
    live: boolean = true

    constructor() {
        this.food = new Food()
        this.snake = new Snake()
        this.scorePanel = new ScorePanel()
    }

    init() {
        const gameEle = document.querySelector('.main')
        // debugger
        document.addEventListener('keyup', this.keyupHandler)

        this.run()
    }

    /**
     * chrome: 上ArrowUp 下ArrowDown 左ArrowLeft 右ArrowRight
     * ie: 上Up 下Down 左Left 右Right
     */
    keyupHandler = (event: KeyboardEvent) => {
        const key = event.key
        // if (key === )
        this.direction = key
        console.log(this.direction)
    }

    // 移动
    run = () => {
        let x = this.snake.X
        let y = this.snake.Y

        switch(this.direction) {
            case 'ArrowUp' :
            case 'Up':
                y -= 10
                break
            case 'ArrowDown' :
            case 'Down':
                y += 10
                break
            case 'ArrowLeft' :
            case 'Left':
                x -= 10
                break
            case 'ArrowRight' :
            case 'Right':
                x += 10
                break
        }

        this.checkEat(x, y)

        try {
            this.snake.X = x
            this.snake.Y = y
        } catch (error) {
            console.log(error.message)
            this.live = false
        }

        
        this.live && setTimeout(this.run, 300 - this.scorePanel.level * 30)
    }

    checkEat(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }
}

export default GameControl
